/**
 * WebSocket管理类
 */
export class WebSocketManager {
    constructor(url, options = {}) {
        this.url = url;
        this.reconnectDelay = options.reconnectDelay || 5000;
        this.maxReconnectAttempts = options.maxReconnectAttempts || Infinity;
        this.reconnectAttempts = 0;
        this.ws = null;
        this.reconnectTimer = null;
        this.onMessageCallback = null;
        this.onStatusChangeCallback = null;
    }

    /**
     * 连接WebSocket
     */
    connect() {
        try {
            this.ws = new WebSocket(this.url);

            this.ws.onopen = () => {
                console.log('WebSocket连接成功');
                this.reconnectAttempts = 0;
                this.updateStatus(true);
                clearTimeout(this.reconnectTimer);
            };

            this.ws.onmessage = (event) => {
                try {
                    console.log('收到消息:', event.data);
                    const message = JSON.parse(event.data);
                    if (this.onMessageCallback) {
                        this.onMessageCallback(message);
                    }
                } catch (e) {
                    console.error('解析消息失败:', e);
                }
            };

            this.ws.onerror = (error) => {
                console.error('WebSocket错误:', error);
            };

            this.ws.onclose = () => {
                console.log('WebSocket连接关闭');
                this.updateStatus(false);
                this.attemptReconnect();
            };

        } catch (e) {
            console.error('WebSocket连接失败:', e);
            this.updateStatus(false);
            this.attemptReconnect();
        }
    }

    /**
     * 尝试重连
     */
    attemptReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
            this.reconnectTimer = setTimeout(() => {
                this.connect();
            }, this.reconnectDelay);
        } else {
            console.error('达到最大重连次数');
        }
    }

    /**
     * 更新连接状态
     */
    updateStatus(isConnected) {
        if (this.onStatusChangeCallback) {
            this.onStatusChangeCallback(isConnected);
        }
    }

    /**
     * 设置消息回调
     */
    onMessage(callback) {
        this.onMessageCallback = callback;
    }

    /**
     * 设置状态变化回调
     */
    onStatusChange(callback) {
        this.onStatusChangeCallback = callback;
    }

    /**
     * 发送消息
     */
    send(data) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(data));
        } else {
            console.warn('WebSocket未连接，无法发送消息');
        }
    }

    /**
     * 关闭连接
     */
    close() {
        clearTimeout(this.reconnectTimer);
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
    }
}